<?php

namespace App\Http\Controllers\VideoAdmin;

use App\Http\Config\ErrorCode;
use App\Http\Controllers\Admin\BaseController;
use App\Models\video\BroadcasterModel;
use App\Models\video\CommentModel;
use App\Models\video\CourseCatalogModel;
use App\Models\video\CourseModel;
use App\Models\video\PlayClassModel;
use App\Models\video\PlayListModel;
use Illuminate\Http\Request;
use App\Library\UpTools;
use App\Models\video\VodApis;
use App\Models\video\VodVideoModel;
use Illuminate\Support\Str;

class VodMediaController extends BaseController
{
    public function __construct(Request $request)
    {
        parent::__construct($request);
    }

    public function getList(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->return_result($this->returnData);
        }
        $db = VodVideoModel::query()->select(["*"])->where("mall_id", $request->mallData["id"]);
        if($request->startTime && $request->endTime){
            $startTime = is_numeric($request->startTime) ? $request->startTime : strtotime($request->startTime);
            $endTime = is_numeric($request->endTime) ? $request->endTime : strtotime($request->endTime);
            $db->whereBetween('create_time', [$startTime, $endTime]);
        }
        if($request->catId){
            $db->where("cat_id", "=", $request->catId);
        }
        if($request->searchText){
            $broadcaster = BroadcasterModel::query()->where("name", "like", "%{$request->searchText}%")
                ->select(["id"])->get();
            foreach ($broadcaster as $it){
                $broadcasterId[] = $it["id"];
            }
            $db->where("title", "like", "%{$request->searchText}%");
            if(!empty($broadcasterId)){
                $db->orWhereIn("broadcaster_id", $broadcasterId);
            }
        }
        $page = $request->page ?: 1;
        $pageSize = $request->pageSize ?: 10;
        $sortName = $request->sortName ? Str::snake($request->sortName) : "create_time";
        $sortOrder = $request->sortOrder ?: "desc";
        $data['count'] = $db->count();
        $data['currentPage'] = $page;
        $data['totalPage'] = ceil(($data['count'])/$pageSize);
        $data['list'] = $db->skip(($page - 1) * $pageSize)->take($pageSize)->orderBy($sortName, $sortOrder)->get();
        if($data['list']){
            $data['list'] = VodVideoModel::transferField($data['list']->toArray());
            foreach ($data["list"] as &$item){
                $item["status"] = $item["status"] ? true : false;
                $item["commentCount"] = CommentModel::getCount(["belong_id" => $item["id"], "status" => 1, "type" => 1]); // 评论次数
                $item["likeCount"] = PlayListModel::getCount(["class_id" => -1, 'mall_id' => $request->mallData["id"], "video_id" => $item["id"]]); // 点赞次数
            }
        }
        $this->returnData["data"] = $data;
        return $this->return_result($this->returnData);
    }

    // 更新媒体信息
    public function saveMediaInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $database = VodVideoModel::query()->select("id","vid","video_duration","broadcaster_id","video_url_list","handle_result")
            ->where("id", $request->id)->orWhere("vid", $request->id)->first();
        if(empty($database)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '媒体文件不存在';
            return $this->return_result($this->returnData);
        }else{
            $database = VodVideoModel::transferField($database->toArray());
        }
        if(empty($request->title)){
            return $this->return_result(ErrorCode::code("params_not_exist", "视频标题"));
        }
        $data = [
            "title" => mb_substr($request->title, 0, 120), "status" => 1, "pay_mode" => $request->payMode ?: 0, "type" => $request->type ?: 1,
            'cat_id' => $request->catId ?: 0, "desc" => ""
        ];
        if(!empty($request->desc)){
            $data["desc"] = mb_substr($request->desc, 0, 300);
        }
        if(!empty($request->coverImgId)){
            $data["cover_img_id"] = $request->coverImgId;
        }
        if(!empty($request->tryTime)){
            $data["try_time"] = $request->tryTime;
        }
        if(!empty($request->payMoney)){
            $data["pay_money"] = $request->payMoney;
        }
        $res = VodApis::getInstance()->modifyMediaInfo($database["vid"], UpTools::transferFields($data));
        if($res["code"] == '0') {
            if($request->payMode == '1'){
                $data["member_mode"] = $request->memberMode ?: '0'; // 会员优惠，0免费，1折扣
            }elseif($request->payMode == '2'){ // 会员免费
                $data["member_mode"] = '0'; // 会员优惠，0免费
            }
            if(VodVideoModel::doUpdate($data, ["id" => $request->id])){
                if ($request->classId) {
                    $res = PlayListModel::query()->select("id", "class_id as classId")
                        ->where(["mall_id" => $request->mallData["id"], "video_id" => $request->id, "broadcaster_id" => $database["broadcasterId"]])
                        ->first();
                    if (!empty($res->id)) {
                        if ($res->classId != $request->classId) {
                            $res = json_decode(json_encode($res), true);
                            PlayListModel::delById($res->id, $res);
                            PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                        }
                    } else {
                        PlayListModel::toAdd(["broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id, "class_id" => $request->classId]);
                    }
                }elseif($request->courseId){
                    $res = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
                        ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
                        ->where(["cc.video_id" => $request->id])
                        ->select("cc.course_id")
                        ->first();
                    if(empty($res->course_id)){
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }elseif($res->course_id != $request->courseId){
                        CourseCatalogModel::delByFilter(['course_id' => $res->course_id, "video_id" => $request->id]);
                        CourseCatalogModel::toAdd(["course_id" => $request->courseId, "broadcaster_id" => $database["broadcasterId"], "video_id" => $request->id]);
                    }
                }
            }
        }else{
            $this->returnData = $res;
        }
        return $this->return_result($this->returnData);
    }

    // 更新媒体信息
    public function saveMediaInfos(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $database = VodVideoModel::getFields("vid", ["id" => $request->id]);
        if(empty($database)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '媒体文件不存在';
            return $this->return_result($this->returnData);
        }
        if(empty($request->title)){
            $this->returnData = ErrorCode::$admin_enum['params_error'];
            $this->returnData['msg'] = '视频标题不能为空';
            return $this->return_result($this->returnData);
        }
        $data = ["title" => mb_substr($request->title, 0, 120)];
        if(!empty($request->desc)){
            $data["desc"] = mb_substr($request->desc, 0, 300);
        }
        if(!empty($request->coverImgId)){
            $data["cover_img_id"] = $request->coverImgId;
        }
        $res = VodApis::getInstance()->modifyMediaInfo($database["vid"], UpTools::transferFields($data));
        if($res["code"] == '0') {
            VodVideoModel::doUpdate($data, ["id" => $request->id]);
        }else{
            $this->returnData = $res;
        }
        return $this->return_result($this->returnData);
    }

    // 更新状态
    public function updateStatus(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        VodVideoModel::doUpdate(["status" => $request->status ?: 0], ["id" => $request->id]);
        return $this->return_result($this->returnData);
    }

    // 获取媒体信息
    public function getMediaInfo(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        $data = VodVideoModel::getFields("*", ["id" => $request->id]);
        if(!empty($data)){
            if($data["type"] == '1') { // 普通视频
                $res = PlayListModel::query()->from(PlayListModel::query()->getModel()->getTable() . " as pl")
                    ->leftJoin(PlayClassModel::query()->getModel()->getTable() . " as pc", "pc.id", "=", "pl.class_id")
                    ->where(["pl.mall_id" => $request->mallData["id"], "pl.video_id" => $request->id, "pl.broadcaster_id" => $data["broadcasterId"]])
                    ->select("pc.id as classId", "pc.name as className")->first();
                $res = json_decode(json_encode($res), true);
                $this->returnData["data"] = is_array($res) ? array_merge($data, $res) : $data;
            }else{ // 课程
                $res = CourseModel::query()->from(CourseModel::query()->getModel()->getTable()." as c")
                    ->leftJoin(CourseCatalogModel::query()->getModel()->getTable()." as cc", "c.id", "=", "cc.course_id")
                    ->where(["cc.video_id" => $request->id, "c.mall_id" => $request->mallData["id"], "c.broadcaster_id" => $data["broadcasterId"]])
                    ->select("c.id as courseId", "c.name as courseName")
                    ->first();
                $res = json_decode(json_encode($res), true);
                $this->returnData["data"] = is_array($res) ? array_merge($data, $res) : $data;
            }
        }else{
            $this->returnData["data"] = [];
        }
        return $this->return_result($this->returnData);
    }

    // 同步删除媒体
    public function deleteMedia(Request $request){
        if ($this->returnData['code'] > 0){
            return $this->returnData;
        }
        VodVideoModel::delByFilter(["id" => $request->id]);
        return $this->returnData;
    }
}
